package com.xujiang.myblog.Base;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.lang.reflect.Field;

/**
 * Created by xujiang on 2017/4/21.
 *
 * 1
 */

public class BaseFragment extends Fragment {

    protected LayoutInflater inflater;
    private View contentView;
    private ViewGroup container;

    public Fragment getFragment(){
        return this;
    }

    protected final String TAG =getFragment().getClass().getSimpleName();

    public static Fragment newInstance(Fragment fragment, Bundle bundle) {
        if (bundle != null) {
            fragment.setArguments(bundle);
        }
        return fragment;
    }


    public Context getApplicationContext() {
        return getActivity().getApplicationContext();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        this.inflater = inflater;
        this.container = container;
        onCreateView(savedInstanceState);
        if(contentView == null){
            return super.onCreateView(inflater,container,savedInstanceState);
        }
        return contentView;
    }

    private void onCreateView(Bundle savedInstanceState) {
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        contentView =null;
        container = null;
        inflater = null;
    }

    public void setContentView(int layoutResID) {
        setContentView(inflater.inflate(layoutResID,container,false));
    }

    public void setContentView(View view) {
        contentView = view;
    }

    public View getContentView() {
        return contentView;
    }

    public View findViewById(int id){
        if(contentView != null){
            return contentView.findViewById(id);
        }
        return null;
    }

    // http://stackoverflow.com/questions/15207305/getting-the-error-java-lang-illegalstateexception-activity-has-been-destroyed
    //反射相关
    @Override
    public void onDetach() {
        super.onDetach();
        try{
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);
        }catch (NoSuchFieldException e){
            throw  new  RuntimeException(e);
        }catch (IllegalAccessException e){
            throw new RuntimeException(e);
        }
    }
}
